package ai.people.netmon.warning.service;

import ai.people.netmon.framework.domain.warning.dto.AnalysisRequestContext;
import ai.people.netmon.framework.model.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 预警分析任务链
 *
 * @author LiGuanNan
 * @date 2022/8/15 10:58
 */
@Slf4j
@Component
public class WarningAnalysisTaskChain {

    @Autowired
    private List<WarningAnalysisTask> warningAnalysisTasks;

    private WarningAnalysisTaskLink analysisTaskHeadLink = null;

    @PostConstruct
    public void init(){
        AtomicReference<WarningAnalysisTaskLink> analysisTaskLink = new AtomicReference<>();
        warningAnalysisTasks = warningAnalysisTasks.stream().sorted(Comparator.comparingInt(o -> ((WarningAnalysisTaskOrder) o).getOrder())).collect(Collectors.toList());
        warningAnalysisTasks.forEach(task->{
            if(analysisTaskHeadLink == null){
                analysisTaskLink.set((WarningAnalysisTaskLink) task);
                analysisTaskHeadLink = analysisTaskLink.get();
            }else {
                analysisTaskLink.set(analysisTaskLink.get().appendNext((WarningAnalysisTaskLink) task).next());
            }
        });
    }

    /**
     * 分析
     *
     * @param requestContext 请求上下文中
     * @return {@link Result}<{@link List}<{@link T}>>
     */
    public <T> Result<List<T>> analysis(AnalysisRequestContext<T> requestContext){
        return analysisTaskHeadLink.doAnalysis(requestContext);
    }

}
